//
//  TWFXCityListViewController.m
//
//
//  Created by Lion User on 13-2-1.
//  Copyright (c) 2013年 Lion User. All rights reserved.
//

#import "TWFXCityListViewController.h"

@interface TWFXCityListViewController ()


@end

BOOL nibsRegistered = NO;

@implementation TWFXCityListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
                
        self.addCityVC = [[[TWFXAddCityViewController alloc] init] autorelease];
        self.favouriteCityList = [[TWFXSingleClass sharedTWFXSingleClass] cityDataList];
        
        
        //当前view在navigation堆栈里不是rootview,所以把该viewpush到navigation堆栈里时,tabbar左边会显示backbarbutton
        //如果给当前view设置了leftbarbutton,会把把backbarbutton覆盖掉,想同时显示两者,需如下设置:
        self.navigationItem.leftItemsSupplementBackButton = YES;
        
        self.title = @"城市列表";
        
        UIBarButtonItem *leftBar = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addCity)] autorelease];
      
        UIBarButtonItem *rightBar = [[[UIBarButtonItem alloc] initWithTitle:@"管理" style:UIBarButtonItemStylePlain target:self action:@selector(editingTableview:)] autorelease];
     
        UIBarButtonItem *backbar = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:nil] autorelease];
        
        
        self.navigationItem.leftBarButtonItem = leftBar;
        self.navigationItem.rightBarButtonItem = rightBar;
        self.navigationItem.backBarButtonItem = backbar;
    
        
        self.singleClass = [TWFXSingleClass sharedTWFXSingleClass];
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    nibsRegistered = NO;
    
    //获取屏幕的高度(不含状态栏)
    CGFloat heightOfScreen = [UIScreen mainScreen].applicationFrame.size.height;

    
    UITableView *tableview = [[[UITableView alloc] initWithFrame:CGRectMake(0.0f,0, 320.0f, heightOfScreen - 44)] autorelease];
    
    tableview.backgroundColor = [UIColor colorWithRed:211/255.0 green:211/250.0 blue:211/255.0 alpha:1];
    tableview.dataSource = self;
    tableview.delegate = self;
    
    self.tableview = tableview;
    
    [self.view addSubview:self.tableview];
    
}



//有文章说用了UINavigationController后，viewWillAppear方法是没有效果的，要用UINavigationControllerDelegate的– navigationController:willShowViewController:animated:方法才可以达到这个目的。
//但在这里,有用啊
//每次显示该view前,先将其属性favouriteCityList属性指向单例类里的cityList属性,和最新数据保持一致
//查看标志量,如果citylist有变,则reload tableview 
-(void) viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"CityListPage"];
    
    self.favouriteCityList = self.singleClass.cityDataList;
    [self.tableview reloadData];
    
    if (self.singleClass.isAddCity) {
        
        self.singleClass.isCityListInfosChangedToRealTime = YES;
        self.singleClass.isCityListInfosChangedToTrend = YES;
        self.singleClass.isAddCity = NO;
        
        [self.tableview reloadData];
    }
}


-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
//    if ([TWFXSingleClass sharedTWFXSingleClass].isCityListChanged) {
//        
//        [TWFXSingleClass sharedTWFXSingleClass].isCityListChanged = NO;
//        self.favouriteCityList = [TWFXSingleClass sharedTWFXSingleClass].cityList;
//        [self.tableview reloadData];
//    }
}


//视图消失前触发,如果tableview处于编辑模式,则退出编辑模式
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"CityListPage"];
    
    
    //退出编辑模式
    if (self.tableview.editing) {
        
        self.navigationItem.rightBarButtonItem.title = @"管理";
        [self.tableview setEditing:NO animated:YES];
        
    }
}


//跳到添加城市页面
-(void) addCity
{
    [self.navigationController pushViewController:self.addCityVC animated:YES];
}


//城市列表管理
-(void)editingTableview:(id)sender
{
    if (self.tableview.editing) {
        
        self.navigationItem.rightBarButtonItem.title = @"管理";
        [self.tableview setEditing:NO animated:YES];
        
    }
    else
    {
        self.navigationItem.rightBarButtonItem.title = @"完成";
        [self.tableview setEditing:YES animated:YES];
        
        
    }
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    float sysVer =[[[UIDevice currentDevice] systemVersion] floatValue];
    
    //ios 6.0 及之后才执行以下代码,ios6.0之前是通过调用viewWillUnload来处理
    if (sysVer>= 6.0f)
    {
        if ([self.view window] == nil)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            
            self.tableview = nil;

            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }

}



#pragma mark- tableview的代理方法



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


/*
 获取tableview指定section的行数
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.favouriteCityList.count;
}


/*
     移动tableviewcell
 */
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    NSUInteger fromRow = [sourceIndexPath row];
    NSUInteger toRow = [destinationIndexPath row];
    
    //调整indexOfCurrent
    if (self.singleClass.indexOfCurrentCity == fromRow)
    {
        self.singleClass.indexOfCurrentCity = toRow;
    }
    else
    {
        //从下往上移
        if (fromRow > toRow)
        {
            if (self.singleClass.indexOfCurrentCity < fromRow && self.singleClass.indexOfCurrentCity >= toRow) {
                
                self.singleClass.indexOfCurrentCity ++;
            }
        }
        //从上往下移
        else
        {
            if (self.singleClass.indexOfCurrentCity <= toRow && self.singleClass.indexOfCurrentCity > fromRow) {
                
                self.singleClass.indexOfCurrentCity --;
            }
        }
    }
    
    
    //把要发生移动的item保存出来,不能直接用 = ; 要retain,否则在下一步的从array里remove该item时,retaincount减1,等于0,对象被释放掉,object就为nil(应该是把),就无法把object添加到新的位置了
    id object = [[self.favouriteCityList objectAtIndex:fromRow] retain];
    [self.favouriteCityList removeObjectAtIndex:fromRow];
    [self.favouriteCityList insertObject:object atIndex:toRow];
    
    [object release];
    
    //发生的变化同时 保存到userdefault里
    [self.singleClass saveCityListToUserDefault];
    [self.singleClass saveIndexOfCurrentCityToUserDefault];
    
    self.singleClass.isCityListInfosChangedToRealTime = YES;
    self.singleClass.isCityListInfosChangedToTrend = YES;
}


//能否移动某一行cell
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


//返回 cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


//当出现删除按钮时，回调该方法显示删除按钮的名字，默认不实现是delete
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"删除";
}


//cell被展示前,设置背景
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row] % 2 == 0) {
        
        [cell setBackgroundColor:[UIColor colorWithRed:210/255.0 green:180/250.0 blue:140/255 alpha:0.3]];
    }
    else
    {
        [cell setBackgroundColor:[UIColor colorWithRed:230/255.0 green:230/250.0 blue:250/255.0 alpha:1]];
    }
    
}


/*
 绘制cell
 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //自定义cell的唯一的用于注册的标识符
    static NSString *WeatherCellIdentifier = @"WeatherCellIdentifier";
    
 //   static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
       
        //注册的是xib文件,直接加载xib文件,就算xib文件是否与类关联,也不会调用类里的构造函数
   //     UINib *nib = [UINib nibWithNibName:@"TWFXWeatherCell" bundle:nil];
   //     [tableView registerNib:nib forCellReuseIdentifier:WeatherCellIdentifier];
        
        //注册是一个类,自定义的cell类
        [tableView registerClass:[TWFXWeatherCell class] forCellReuseIdentifier:WeatherCellIdentifier];
        
        nibsRegistered = YES;
    }

    //当可以复用队列里的cell为nil时,会自动调用自定义cell类的构造方法?
    TWFXWeatherCell *cell = (TWFXWeatherCell*)[tableView dequeueReusableCellWithIdentifier:WeatherCellIdentifier];
    
    NSInteger row = [indexPath row];
    TWFXStruct_AllWeatherInfo *cityInfo = nil;
    cityInfo = [self.favouriteCityList objectAtIndex:row];
    

    NSString *str_cityShow;
    if (cityInfo.realTimeWeatherInfo.temp != nil && cityInfo.futureWeatherInfo.img_title1 != nil) {
        
        str_cityShow = [NSString stringWithFormat:@"%@ %@ %@℃", cityInfo.countName, cityInfo.futureWeatherInfo.img_title1, cityInfo.realTimeWeatherInfo.temp];
        
    }
    else
    {
        str_cityShow = [NSString stringWithFormat:@"%@", cityInfo.countName];
    }
    
    NSString *str_futureWeahter;
    if (cityInfo.futureWeatherInfo.date_y != nil)
    {
        
        NSString* str = cityInfo.futureWeatherInfo.date_y;
        str = [str stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
        str = [str stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
        str = [str stringByReplacingOccurrencesOfString:@"日" withString:@""];
        
        str_futureWeahter = [NSString stringWithFormat:@"%@ 同步",str];
        
    }
    else
    {
        str_futureWeahter = @"未同步";
    }
    
    cell.labelCityName.text = str_cityShow;
    cell.labelCityWeather.text = str_futureWeahter;
    [cell.image_weather setImage:[UIImage imageNamed:cityInfo.futureWeatherInfo.img1]];
    
    
    return cell;

}


/*
 可否选中某行
 把选中的城市保存到 当前城市 里(userdefault), 并更新当前城市 页面
 */
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    return indexPath;
}


//选中完某一个cell之后,返回上一个页面
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TWFXStruct_AllWeatherInfo* tempCity = [TWFXSingleClass sharedTWFXSingleClass].cityDataList[indexPath.row];
    
    NSString *countID = [TWFXSingleClass sharedTWFXSingleClass].currentCityInfo.countID;
    
    //如果选中的城市不是当前展示的城市,则把该城市保存为新的当前城市
    if (![tempCity.countID isEqualToString:countID]) {
        
        self.singleClass.indexOfCurrentCity = [indexPath row];
        [self.singleClass saveIndexOfCurrentCityToUserDefault];
        
        //标记量,表明当前城市发生变化
        self.singleClass.isCityListInfosChangedToRealTime = YES;
        self.singleClass.isCityListInfosChangedToTrend = YES;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
}




/*
 进入编辑模式后,首先要选则一种具体的模式:删除 \ 增加 \ 移动.
 默认是删除模式,既是在行的左边显示一个红色的删除按钮
 */
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //返回删除模式.
    return UITableViewCellEditingStyleDelete;
}



/*
 进入编辑模式  选择了具体的删除 增加  编辑模式后,执行编辑
 按下delete键后执行
 */
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];

    if (self.favouriteCityList.count == 1) {
        
        NSLog(@"最后一个城市,没得删了");
        return;
    }
    
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        TWFXStruct_AllWeatherInfo *tempCityWeather = self.favouriteCityList[indexPath.row];
        TWFXStruct_AllWeatherInfo *currentCity = self.singleClass.cityDataList[self.singleClass.indexOfCurrentCity];
        
        // ==  比较的是两个对象是否是同一个对象
        if ([tempCityWeather.countID isEqualToString:currentCity.countID]) {
            
            [self.favouriteCityList removeObjectAtIndex:row];
        
            self.singleClass.indexOfCurrentCity = 0;
            
            [self.singleClass saveIndexOfCurrentCityToUserDefault];
            [self.singleClass saveCityListToUserDefault];
            
            self.singleClass.isCityListInfosChangedToRealTime = YES;
            self.singleClass.isCityListInfosChangedToTrend = YES;

        }
        //要调整 indexOfCurrentCity 的值
        else
        {
            if(self.singleClass.indexOfCurrentCity > row)
            {
                self.singleClass.indexOfCurrentCity --;
            }
            
            [self.favouriteCityList removeObjectAtIndex:row];
            [self.singleClass saveCityListToUserDefault];
            [self.singleClass saveIndexOfCurrentCityToUserDefault];
            
            self.singleClass.isCityListInfosChangedToRealTime = YES;
            self.singleClass.isCityListInfosChangedToTrend = YES;

        }
        
        /*
         创建一个NSArray数组,里面放的是一组 NSIndexPath 类型 的对象,作为tableview进行操作的对象的索引
         */
        NSArray *array = [NSArray arrayWithObjects:indexPath,nil];
        
        //这样子删除有动画效果,直接reloadData没有动画效果.但这样子会引起两个cell的背景颜色一样,而reload则不会
        [tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}



- (void)dealloc
{
    [_addCityVC release];
    [_tableview release];
    [_favouriteCityList release];
    
    [super dealloc];
}

@end
